package com.scalar.chiptrack.adaptor.ikanos.po;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.finance.openpo.PurchaseOrder;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.ScalarException;

import java.util.ArrayList;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 24 Jul, 2009
 * Time: 12:26:31 PM
 * To change this template use File | Settings | File Templates.
 */
public class PODataParser extends JobHandler implements AdaptorConstants
{
    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public  PODataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = ConfigManager.getPoFileDir();

            if ( m_dataOutputDir != null )
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

                m_parserLogger= AdaptorUtils.getDataParserLogger( m_dataOutputDir,"PO" );

                AdaptorUtils.setLogger( m_parserLogger );

            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading PO output directory details from database, Exception: " + se );
            System.out.println( "ERROR!! ERROR!! ERROR!! Exception while loading PO output directory details from database, Exception: " + se );
        }
    }
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new PODataParser().execute();
        }
        catch ( Exception e )
        {
            throw e;
        }
    }
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader( "PO", CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done" );
        File dataoutDir  = new File( m_dataOutputDir );

        File[] fileList = dataoutDir.listFiles();

        if ( ( fileList == null ) || (fileList.length <= 3))
        {
            log("No file found in directory: " + dataoutDir);
            System.out.println("No file found in directory: " + dataoutDir );
            throw new ScalarException("No file found in directory: " + dataoutDir+ "----\n\n" );
        }

        ArrayList<File> successFileList = new ArrayList<File>();

        boolean success = false;

        for ( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() )
            {
                continue;
            }

            try
            {
                if ( fileList[i].getName().startsWith( POAdaptor.FILE_NAME )  || fileList[i].getName().indexOf( POAdaptor.FILE_NAME )  != -1)
                {
                     ArrayList<PurchaseOrder> poList = parsePOReport( fileList[i].getAbsolutePath() );

                     if ( poList != null && poList.size() > 0 )
                     {
                         PurchaseOrderDAO.savePODetails( null, poList);
                     }

                    successFileList.add(fileList[i]);
                }

                success = true;
            }
            catch (Exception e)
            {
                success = false;
                log("Exception while parsing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                e.printStackTrace();
                throw e;
            }
        }

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( POAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        // transaction 9
        try
        {
            if (success)
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, POAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println("SUCCESSFULLY UPDATED IN THE DATABASE");
            }
        }
        catch (ScalarException se)
        {
            success = false;  //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, POAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log("WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se);
            throw se;
        }

        // Step 10
        // Move the successful files to 'done' directory
        if (success)
        {
            AdaptorUtils.moveFilesToDone( successFileList, doneDestDir);
        }
    }

    private ArrayList<PurchaseOrder> parsePOReport (String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result = null;
        int poQuantity = 0;
        ArrayList<PurchaseOrder> poList = new ArrayList<PurchaseOrder>();
        PurchaseOrder purchaseOrder = null;
        try
        {
            File detailWipFile = new File( fileName );
            if ( !detailWipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            Parser parser = ParserFactory.getXLSParser( detailWipFile );

            ((XLSParserImpl)parser).setHeaderRowIdx(2);
            ((XLSParserImpl)parser).setDataStartRowIdx(3);

            result = parser.parse();
            //System.out.println("result = " + result.getHeadings() );
            while ( result.next() )
            {
                purchaseOrder = new PurchaseOrder();

                purchaseOrder.setVendorName(  result.getString("Vendor") );

                if ( purchaseOrder.getVendorName() != null && result.getString ( "Po Number" ) != null && result.getString ( "Po Number" ).trim().length() > 0 )
                {
                    if ("OPEN".equalsIgnoreCase(result.getString ( "PO Line Close Code" ).trim() ) )
                    {
                        purchaseOrder.setPurchaseOrderNumber( result.getInt ( "Po Number" ) +"");
                        purchaseOrder.setPoLineItemNo( result.getInt("Line Num") +"");
                        
                        if ( "STANDARD".equalsIgnoreCase(result.getString("Po Type") ) )
                        {
                            purchaseOrder.setPurchaseOrderType(  2  );
                        }
                        purchaseOrder.setPurchaseOrderDate(StringUtils.formatDateToString( result.getDate("Po Date") ) );
                        try
                        {
                        	poQuantity = result.getInt("Quantity Ordered") - result.getInt("Quantity Cancelled") - result.getInt("Quantity Delivered");
                        }
                        catch(Exception e)
                        {
                        	poQuantity = 0;	
                        }
                        purchaseOrder.setRequestedQty(poQuantity);
                        purchaseOrder.setPoUnitCost( result.getDouble("Unit Price"));
                        purchaseOrder.setStatus(result.getString("Authorization Status"));
                        purchaseOrder.setPartNumber( result.getString("Item Name").indexOf("-") != -1 ? result.getString("Item Name").substring(0, result.getString("Item Name").indexOf("-") ) : result.getString("Item Name") );
                        if ( purchaseOrder.getPartNumber() != null && purchaseOrder.getPartNumber().indexOf(".") != -1 )
                        {
                            purchaseOrder.setPartNumber( purchaseOrder.getPartNumber().substring(0, purchaseOrder.getPartNumber().indexOf(".") ) );
                        }
                        purchaseOrder.setRequestedDate( StringUtils.formatDateToString( result.getDate("Need By Date") ) );
                        purchaseOrder.setPsType( WIP_TYPE_FAB );
                        poList.add( purchaseOrder );
                    }
                    //System.out.println ( "DOULBLE VALUE : " + result.getDouble ( "Q109" ) + ":   " + result.getDouble ( "Sort" )  + ":   " + result.getDouble("Assy") + " :    " + result.getDouble("Test") + " :    " +  result.getDouble("BE (Dry Pack)") );
                    //System.out.println ( "DOULBLE VALUE YIELD"  + Math.round(result.getDouble("Sort Yield") * 100 ) + " :  " + Math.round(result.getDouble("Assy Yield") * 100 ) + " :  "+Math.round(result.getDouble("Test Yield") * 100 ) );
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        System.out.println("PO List Size " + poList.size());
        return  poList;
    }

    private void log( String message )
    {
      if ( message == null ) return;

      if ( m_parserLogger != null )
      {
          m_parserLogger.logDebug( message + LINE_SEPARATOR );
      }
      else
      {
          System.out.println( message );
      }
    } // end of log method
}

